package com.xueyu.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xueyu.domain.CacheManager;
import com.xueyu.dao.UserMapper;
import com.xueyu.dao.roleDao;
import com.xueyu.domain.Products.ProductsBean;
import com.xueyu.domain.SupplierBean;
import com.xueyu.domain.drug.drug;
import com.xueyu.domain.goods.Product;
import com.xueyu.domain.role;
import com.xueyu.util.ResultBean;
import com.xueyu.domain.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/user")
public class userVueController {
    @Autowired
    private UserMapper UserMapper;
    @Autowired
    private roleDao roleDao;

    @RequestMapping(value = "/uploadPic")
    public  ResultBean add(HttpServletRequest request, UserVo UserVo, @RequestPart(value = "pic", required = false) MultipartFile[] pic) throws Exception{
        ResultBean resultBean = new ResultBean();
        if(pic!=null) {
            for (MultipartFile file : pic) {
                String picName = UUID.randomUUID().toString();
                // 截取文件的扩展名(如.jpg)
                String oriName = file.getOriginalFilename();
                String extName = oriName.substring(oriName.lastIndexOf("."));
                String path = request.getSession().getServletContext().getRealPath("\\");
                //日期处理
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String sdate = sdf.format(date);
                String dirName = "\\upload\\" + sdate + "\\";
                File dirFile = new File(path + dirName);
                if (!dirFile.exists()) {
                    dirFile.mkdirs();
                }
                String newFileName = picName + extName;
                File targetFile = new File(path + dirName, newFileName);
                file.transferTo(targetFile);
                String path1 = dirName + newFileName;
                System.out.println("path=" + path1);

                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String currentTime = sdf1.format(date);
                UserVo.setDrugPic(path1);
            }
        }
        if(UserVo.getUserId()==0) {
            UserMapper.insert(UserVo);
        }else {
            UserMapper.updateById(UserVo);
        }
        return resultBean;
    }






//    @RequestMapping(value = "/uploadPic")
//    public  Map<String, Object> uploadPic(@RequestBody UserVo UserVo) throws Exception{
//            Map<String, Object> map = new HashMap<>();
//        if(UserVo.getUserId()==0) {
//            if (UserMapper.insert(UserVo) == 1) {
//                map.put("code", 200);
//                map.put("msg", "新增成功");
//            } else {
//                map.put("code", 500);
//                map.put("msg", "新增失败!!");
//            }
//        }else {
//            if (UserMapper.updateById(UserVo)==1) {
//                map.put("code", 200);
//                map.put("msg", "修改成功");
//            } else {
//                map.put("code", 500);
//                map.put("msg", "修改失败!!");
//            }
//        }
//        return map;
//    }
//




    //列表
    @RequestMapping("/schoolList")
    @ResponseBody
    public List<UserVo> schoolList() {
        List<UserVo> schoolList = UserMapper.selectList(null);



        return schoolList;
    }


//    //状态
//    @RequestMapping("/status/{slid}/{status}")
//    public ResultBean id0(@PathVariable("slid") String slid,@PathVariable("status") String status) {
//        Map<String, Object> map = new HashMap<>();
//        LambdaUpdateWrapper<UserVo> updateWrapper = new LambdaUpdateWrapper<>();
//        updateWrapper.set(UserVo::getStatus, status)
//                .eq(UserVo::getSlid, slid);
//         schoolDao.update(null, updateWrapper);
//        return new ResultBean();
//    }


    //删除
    @RequestMapping("/del/{slid}")
    public ResultBean del(@PathVariable("slid") int slid){
        UserMapper.deleteById(slid);
        return new ResultBean();
    }



    @RequestMapping("/update/{slid}")
    public Map<String, Object> batchById(@PathVariable("slid") int slid){
        ResultBean resultBean = new ResultBean();
        if(slid>0){
        QueryWrapper<UserVo> queryWrapper = Wrappers.query();
        queryWrapper.eq("userId", slid);
        List<UserVo> schoolList = UserMapper.selectList(queryWrapper);
        resultBean.put("data",schoolList);
        }
        return resultBean;
    }



         //分页.条件查询.
        @RequestMapping("/fy")
        public ResultBean fy(@RequestBody  Map map) {
        int current = (Integer)map.get("Current");
        int size = (Integer)map.get("size");
        Page<UserVo> page = new Page<>(current, size);
        QueryWrapper<UserVo> queryWrapper = createSchoolQueryWrapper(map);
        page = UserMapper.selectPage(page, queryWrapper);
        List<UserVo> list = page.getRecords();
            //遍历药品列表
            for (UserVo Drug : list) {
                // 获取药品的分类id
                Long categoryId = Long.valueOf(Drug.getRole());
                // 根据分类id查询对应的分类信息
                role category = roleDao.selectById(categoryId);
                // 如果分类存在，则将分类名称设置到药品表中
                if (category != null) {
                    Drug.setRole(category.getRole());
                }

            }

            List<role> schoolList = roleDao.selectList(null);




            ResultBean resultBean = new ResultBean();
        resultBean.put("page",page);
        resultBean.put("list",list);
        resultBean.put("list2",schoolList);
        return resultBean;
    }
    @RequestMapping("/zd")
    public ResultBean zd(@RequestBody  Map map)
    {
        QueryWrapper<UserVo> queryWrapper = createSchoolQueryWrapper(map);
        List<UserVo> list = UserMapper.selectList(queryWrapper);
        ResultBean resultBean = new ResultBean();
        resultBean.put("list",list);
        return resultBean;
    }

    @RequestMapping("/getpassword")
     public ResultBean getpassword(@RequestBody  Map  map) {
        ResultBean resultBean = new ResultBean();
        String password = (String)map.get("password");
        String newpassword = (String)map.get("newpassword");
        List<UserVo> cachedUserList = (List<UserVo>) CacheManager.get("userList");
        for (UserVo user : cachedUserList) {
            System.out.println(user.getUserName());
            System.out.println(user.getPassWord());
            if(user.getPassWord().equals(password)){
               user.setPassWord(newpassword);
               UserMapper.updateById(user);
            }else{
                resultBean.put("codes","201");
                resultBean.put("msg","旧密码不一致");

            }
        }
        return resultBean;
    }
    @RequestMapping("/password")
    public ResultBean resetPassword(@RequestBody List<Long> ids) {
        ResultBean resultBean = new ResultBean();
        // 查询选中的用户
        List<UserVo> users = UserMapper.selectUsersByIds(ids);
        // 更新用户的初始密码为1234
        int count = UserMapper.batchUpdatePassword(ids, "1234");
        return resultBean;
}
    //封装好的查询条件
    public QueryWrapper<UserVo> createSchoolQueryWrapper(Map map) {
        String userId =  (String)map.get("slid");
        String userName =  (String)map.get("userName");
        String age =  (String)map.get("age");
        QueryWrapper<UserVo> queryWrapper = Wrappers.query();
        if (userId != null && !"".equals(userId)) {
            queryWrapper.eq("userId", userId);
        }
        if (userName != null && !"".equals(userName)) {
            queryWrapper.like("userName", "%" + userName + "%");
        }
        if (age != null && !"".equals(age)) {
            queryWrapper.like("age", "%" + age + "%");
        }
        return queryWrapper;
    }





}




